package com.home.communication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.home.activities.ResourceActivity;
import com.home.constants.Consts;
import com.home.jsonhelpers.JsonArrayAdapter;
import com.home.jsonhelpers.JsonRequestObject;
import com.home.jsonhelpers.ResourceJsonArrayAdapter;
import com.home.rhclient.MainController;
import com.home.rhtester.R;

public class ConnectionHandlers {

	static public class ListResourceHandler extends Handler {

		ListView listView;

		public ListResourceHandler(ListView listView) {
			this.listView = listView;

		}

		public ListResourceHandler() {

		}

		public void setListView(ListView listView) {
			this.listView = listView;
		}

		@Override
		public void handleMessage(Message msg) {
			Bundle returnBundle = msg.getData();

			try {
				JSONObject jsonMessage = new JSONObject(returnBundle.getString("response"));
				int messageCode = jsonMessage.getInt(Consts.JSON_MESSAGE_CODE);
				if (messageCode == Consts.RESPONSE_RESULT) {
					JSONArray resources = jsonMessage.getJSONArray(Consts.JSON_ARRAY);

					ResourceJsonArrayAdapter adapter = new ResourceJsonArrayAdapter(resources, listView.getContext(), Consts.RESOURCE_NAME, Consts.RESOURCE_ID, R.drawable.hardware, R.layout.listview_row);

					if (listView.getHeaderViewsCount() == 0) {
						LayoutInflater vi = (LayoutInflater) listView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						View header = (View) vi.inflate(R.layout.listview_header, null);
						TextView headerText = (TextView) header.findViewById(R.id.list_header);
						headerText.setText("Resources:");
						listView.addHeaderView(header);
						listView.setHeaderDividersEnabled(true);
					}

					listView.setAdapter(adapter);
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	static public class ListResourceCategoriesHandler extends Handler {
		private ListView listView;
		private int categoryId;

		public ListResourceCategoriesHandler(ListView listView, int catId) {
			this.listView = listView;
			categoryId = catId;
		}

		public ListResourceCategoriesHandler() {

		}

		public void setListView(ListView listview) {
			this.listView = listview;
		}

		@Override
		public void handleMessage(Message msg) {
			Bundle returnBundle = msg.getData();
			try {
				JSONObject jsonMessage = new JSONObject(returnBundle.getString("response"));
				int messageCode = jsonMessage.getInt(Consts.JSON_MESSAGE_CODE);
				if (messageCode == Consts.RESPONSE_RESULT) {
					JSONArray categories = jsonMessage.getJSONArray(Consts.JSON_ARRAY);

					JsonArrayAdapter adapter = new JsonArrayAdapter(categories, listView.getContext(), Consts.RCATEGORY_NAME, Consts.RCATEGORY_ID, R.drawable.system_folder, R.layout.listview_categories_row);

					if (listView.getHeaderViewsCount() == 0) {// Prevent
																// multiple
																// header views
						LayoutInflater vi = (LayoutInflater) listView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						View header = (View) vi.inflate(R.layout.listview_header, null);
						TextView headerText = (TextView) header.findViewById(R.id.list_header);
						headerText.setText("Categories");
						listView.addHeaderView(header);
						listView.setHeaderDividersEnabled(true);
					}

					listView.setAdapter(adapter);

				} else {
					Log.e("ListResourceCategoriesHandler", "Error message code: " + messageCode);
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	static public class StartResouceHandler extends Handler {
		private ResourceActivity resourceActivity;
		private long reservationLength, serverTime, oldClientTime, currentTime, latency, clientServerDelta, localReservationLength;

		public StartResouceHandler(ResourceActivity activity) {
			this.resourceActivity = activity;
		}

		public StartResouceHandler() {
		}

		public void setResourceActivity(ResourceActivity resActivity) {
			resourceActivity = resActivity;
		}

		@Override
		public void handleMessage(Message msg) {
			Bundle returnBundle = msg.getData();
			try {
				JSONObject jsonMessage = new JSONObject(returnBundle.getString("response"));
				int messageCode = jsonMessage.getInt(Consts.JSON_MESSAGE_CODE);
				if (messageCode == Consts.RESPONSE_CONFIRM) {
					reservationLength = jsonMessage.getLong(Consts.RESERVATION_LENGTH);
					serverTime = jsonMessage.getLong(Consts.SERVER_TIME);
					oldClientTime = jsonMessage.getLong(Consts.CLIENT_TIME);
					currentTime = MainController.GetInstance().GetCurrentDate().getTime();
					latency = (currentTime - oldClientTime) / 2;
					clientServerDelta = serverTime - currentTime + latency;
					localReservationLength = reservationLength - latency;

					resourceActivity.startNotificationService(localReservationLength);

					Toast.makeText(resourceActivity, "Resource Started", Toast.LENGTH_SHORT).show();
					resourceActivity.setResult(Consts.RESULT_REFRESH_REQUESTED, new Intent());
					resourceActivity.finish();
				} else {
					Toast.makeText(resourceActivity, "Resource Failed to Start", Toast.LENGTH_SHORT).show();
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	static public class RestartResouceHandler extends Handler {
		private ResourceActivity activity;

		public RestartResouceHandler(ResourceActivity activity) {
			this.activity = activity;
		}

		public RestartResouceHandler() {
		}

		public void setResourceActivity(ResourceActivity resActivity) {
			activity = resActivity;
		}

		@Override
		public void handleMessage(Message msg) {
			Bundle returnBundle = msg.getData();
			try {
				JSONObject jsonMessage = new JSONObject(returnBundle.getString("response"));
				int messageCode = jsonMessage.getInt(Consts.JSON_MESSAGE_CODE);
				if (messageCode == Consts.RESPONSE_CONFIRM) {
					Toast.makeText(activity, "Resource Restarted", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(activity, "Resource Failed to Restart", Toast.LENGTH_SHORT).show();
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	static public class ResourceDetailsHandler extends Handler {
		private ResourceActivity resourceaAtivity;

		public ResourceDetailsHandler(ResourceActivity resActivity) {
			resourceaAtivity = resActivity;
		}

		public ResourceDetailsHandler() {
		}

		public void setResourceActivity(ResourceActivity resActivity) {
			resourceaAtivity = resActivity;
		}

		@Override
		public void handleMessage(Message msg) {
			Bundle returnBundle = msg.getData();
			try {
				JSONObject jsonMessage = new JSONObject(returnBundle.getString("response"));

				int resourceState = jsonMessage.getInt(Consts.RESOURCE_STATE);

				switch (resourceState) {
				case Consts.RESOURCE_NOT_ACTIVE:

					break;
				case Consts.RESOURCE_ACTIVE:
					int resourceOwnershipState = jsonMessage.getInt(Consts.RESOURCE_OWNERSHIP);
					if (resourceOwnershipState == Consts.RESOURCE_OWNED) {
						//resourceaAtivity.showRestartButton();
						resourceaAtivity.setAvailableStateOnDetailsRequest();
					}
					else
					{
						resourceaAtivity.setUnavailableStateOnDetailsRequest();
					}
					long activationLength = jsonMessage.getLong(Consts.RESERVATION_LENGTH);
					long servertime = jsonMessage.getLong(Consts.SERVER_TIME);
					long oldClientTime = jsonMessage.getLong(Consts.CLIENT_TIME);

					long currentTime = MainController.GetInstance().GetCurrentDate().getTime();
					long latency = (currentTime - oldClientTime) / 2;
					long clientServerDelta = servertime - currentTime + latency;

					resourceaAtivity.updateResourceTimer(latency, activationLength);

					break;
				case Consts.RESOUCE_NOT_AVAILABLE:
					Toast.makeText(resourceaAtivity, "Resouce temporarly not available", Toast.LENGTH_LONG).show();
					resourceaAtivity.finish();
					break;
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

}
